/*
 * Copyright 2021 TiKV Project Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.webank.tikv.region;

import com.webank.tikv.kvproto.Metapb;

import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

public class TiStore implements Serializable {

    public final static String ZONE_LABEL = "zone";

    private final Metapb.Store store;
    private final AtomicBoolean reachable;
    private final AtomicBoolean valid;

    private String zone;

    public TiStore(Metapb.Store store) {
        this.store = store;
        this.reachable = new AtomicBoolean(true);
        this.valid = new AtomicBoolean(true);
        // extract label
        for (Metapb.StoreLabel label : store.getLabelsList()) {
            if (ZONE_LABEL.equals(label.getKey())) {
                zone = label.getValue();
            }
        }
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof TiStore)) {
            return super.equals(obj);
        }
        TiStore other = (TiStore) obj;
        return this.store.equals(other.store);
    }

    @Override
    public int hashCode() {
        return Objects.hash(store);
    }

    @Override
    public String toString() {
        return String.format("[Store:%d, Valid:%s, Reachable:%s]",
            store.getId(), valid.get(), reachable.get());
    }

    public void markUnreachable() {
        reachable.set(false);
    }

    public void markReachable() {
        reachable.set(true);
    }

    public boolean isReachable() {
        return reachable.get();
    }

    public boolean isValid() {
        return valid.get();
    }

    public void markInvalid() {
        valid.set(false);
    }

    public Metapb.Store getStore() {
        return store;
    }

    public String getAddress() {
        return store.getAddress();
    }

    public long getId() {
        return store.getId();
    }

    public String getZone() {
        return zone;
    }

}
